package com.qw.qrweb.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qw.qrweb.mapper.ContentMapper;
import com.qw.qrweb.mapper.LogMapper;
import com.qw.qrweb.model.dto.DayVisits;
import com.qw.qrweb.model.dto.RegionDTO;
import com.qw.qrweb.model.entity.LogEntity;
import com.qw.qrweb.service.LogService;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LogServiceImpl implements LogService {

    @Resource
    LogMapper logMapper;

    @Resource
    ContentMapper contentMapper;

    @Override
    public int addLog(String ip) {
        LocalDateTime time = LocalDateTime.now();
        logMapper.addLog(ip, time);
        return 0;
    }

    @Override
    public List<LogEntity> getLogs() {
        return logMapper.getLogs();
    }

    @Override
    public List<LogEntity> getLogsToday() {
        return logMapper.getLogsToday();
    }

    @Override
    public List<LogEntity> getLogsLastHour() {
        return logMapper.getLogsLastHour();
    }

    @Override
    public List<DayVisits> getVisitsLastWeek() {
        return logMapper.getVisitsLastWeek();
    }

    @Override
    public Map<String, Integer> getHourlyTrafficStats() {
        // 调用 mapper 获取数据，这里假设你有一个方法叫做 getHourlyTrafficStats
        List<LogEntity> logs = logMapper.getHourlyTrafficStatsToday();

        // 处理并返回统计数据
        Map<String, Integer> stats = new HashMap<>();
        // 这里假设 LogEntity 有一个 getHour 方法和 getCount 方法
        for (LogEntity log : logs) {
            stats.put(log.getHour(), log.getCount());
        }
        return stats;
    }

    @Override
    public List<LogEntity> getLogsLast5Minutes() {
        return logMapper.getLogsLast5Minutes();
    }

    @Override
    public List<LogEntity> getLogsLast10Minutes() {
        return logMapper.getLogsLast10Minutes();
    }

    @Override
    public List<LogEntity> getLogsLast30Minutes() {
        return logMapper.getLogsLast30Minutes();
    }

    @Override
    public List<RegionDTO> getLogsRegions() {
        return logMapper.getLogsRegions();
    }

    // 调用第三方服务获取 IP 对应的地区信息的方法
    @Override
    public String getRegionByIp(String ip) {
        RestTemplate restTemplate = new RestTemplate();
        ObjectMapper objectMapper = new ObjectMapper();
        String url = "https://searchplugin.csdn.net/api/v1/ip/get?ip=" + ip;
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JsonNode rootNode = objectMapper.readTree(response.getBody());
                JsonNode codeNode = rootNode.path("code");
                if (codeNode.asInt() == 200) {
                    JsonNode dataNode = rootNode.path("data");
                    JsonNode addressNode = dataNode.path("address");
                    String address = addressNode.asText();
                    // 可能需要进一步处理字符串来提取省份信息
                    return address.split(" ")[1]; // 假设地址格式始终如"中国 浙江 杭州 阿里云"这样
                }
            }
        } catch (Exception e) {
            // 处理异常情况
            e.printStackTrace();
        }
        return "未知地区"; // 如果无法获取地区，则返回默认值
    }

    // 更新 region 为空的记录
    @Override
    @Scheduled(fixedDelay = 300000)
    public void updateRegionsForIps() {
        List<LogEntity> logs = logMapper.findLogsWithEmptyRegion();
        for (LogEntity log : logs) {
            String region = getRegionByIp(log.getIp());
            log.setRegion(region);
            logMapper.updateLogRegion(log.getId(), region);
        }
    }

    @Override
    public int countNewContentViews() {
        String latestUpdateTimeStr = contentMapper.getLatestUpdateTime();
        LocalDateTime latestUpdateTime = parseUpdateTime(latestUpdateTimeStr);
        return logMapper.countViewsAfterUpdateTime(latestUpdateTime);
    }

    private LocalDateTime parseUpdateTime(String updateTimeStr) {
        // 根据您的具体格式解析字符串为LocalDateTime
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年M月d日 H点mm分ss秒");

        return LocalDateTime.parse(updateTimeStr, formatter);
    }

}
